﻿<!DOCTYPE html>
<html>
<head>
<title>the5fire-backbone-collection</title>
</head>
<body>
</body>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="http://www.css88.com/doc/underscore/underscore-min.js"></script>
<script src="http://www.css88.com/doc/underscore/backbone-min.js"></script>
<script type="text/javascript">
(function ($) {  
    //collection是一个简单的models的有序集合  
    //1、一个简单的例子  
      
    Book = Backbone.Model.extend({  
        default : {  
            title:'default'  
        },  
        initialize: function(){  
            //alert('Hey, you create me!');  
        }  
    });  
    BookShelf = Backbone.Collection.extend({  
        model : Book  
    });  
      
    var book1 = new Book({title : 'book1'});  
    var book2 = new Book({title : 'book2'});  
    var book3 = new Book({title : 'book3'});  
      
    //var bookShelf = new BookShelf([book1, book2, book3]); //注意这里面是数组,或者使用add  
    var bookShelf = new BookShelf;  
    bookShelf.add(book1);  
    bookShelf.add(book2);  
    bookShelf.add(book3);  
    bookShelf.remove(book3);  
    /* 
    for(var i=0; i<bookShelf.models.length; i++) { 
        alert(bookShelf.models[i].get('title')); 
    } 
    */  
    //基于underscore这个js库，还可以使用each的方法获取collection中的数据  
    bookShelf.each(function(book){  
        alert(book.get('title'));  
    });  
      
    //2、使用fetch从服务器端获取数据,使用reset渲染  
    showAllBooks = function(){  
        bookShelf.each(function(book){  
    // 将book数据渲染到页面。  
            console.log(JSON.stringify(book));
        });  
    }  
    bookShelf.bind('reset', showAllBooks);  
    bookShelf.fetch({url:'/getbooks/',success:function(collection,response){  
        collection.each(function(book){  
            alert(book.get('title'));     
        });   
    },error:function(){  
        alert('error');  
    }});  
    //上述代码仅仅均为可正常执行的代码，不过关于服务器端的实例在后面会有。  
})(jQuery);  
</script>
</html>
